package com.salmon.security.rbac.service.impl;

import com.salmon.security.rbac.service.RbacService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service("rbacService")
@Transactional(readOnly = true)
public class RbacServiceImpl implements RbacService {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        // 在APP环境中使用时 principal 是字符串，在浏览器模式下 principal 是 UserDetails 类型
        // APP 环境下使用token的方式来验证多有的服务，如果在APP要使用RBAC模型，还原到 tag 为 v2.2 的版权
        Object principal = authentication.getPrincipal();
        boolean hasPermission = false;
        if(principal instanceof UserDetails) {
            String username = ((UserDetails)principal).getUsername();
            //TODO 需要根据具体的业务进行填写 根据获取的用户名去验证 username
            List<String> urls = new ArrayList<>();
            //TODO 测试填写 需要删
            urls.add("/user/*");
            for (String url : urls) {
                if(antPathMatcher.match(url, request.getRequestURI())) {
                    hasPermission = true;
                    break;
                }
            }
        }
        return hasPermission;
    }
}
